package com.roc.web.action.yycard;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.YYCardBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ScanCodeDictionary;
import com.roc.pojo.TblMchtContact;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblMchtPicture;
import com.roc.service.IMerchantServices;
import com.roc.service.IYYCardService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.HttpClientUtil;
import com.roc.util.MD5Utils;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/opcard")
public class YYCardAction extends PaginationBaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 258704556391492131L;

	private Logger logger=LogManager.getLogger(YYCardAction.class);
	
	@Autowired
	private IYYCardService yyCardService;
	@Autowired
	private IPowerInfoService powerInfo;
	private TblMchtInf merinfo;
	private List<TblMchtPicture> pictrueList;
	private TblMchtContact contact;
	private String scanCodeFlag;//扫码标志
	private YYCardBean yycard;
	private String openType;//开通类型
	private String stairname;//一级类目
	private String moversname;//二级类目
	private List<Map<String,Object>> listMap;
	private List<ScanCodeDictionary> dicMap;
	private String msg;//开通提示
	private String flag;//是否重新开通标志
	private String qrUrl;//二维码路径
	private String scode;//传递过来的验证码
	private String realCode;//生成的验证码
	private ScanCodeDictionary dic;
	private String opMchtCd;
	/**
	 * 初始化页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { 
			@Result(name = "success", location = "/pages/yycard/openCard.jsp"),
			@Result(name = "again", location = "/pages/yycard/againCard.jsp"),
			@Result(name="error",location="/error.jsp")
			})
	public String initCardPage(){
		try{
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.SYSTEM.getCode())||
					op.getRoleType().equals(Role.O_MANAGER.getCode())||
					op.getRoleType().equals(Role.AGENT.getCode())||
					op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
				if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){//运营先行判断
					String roleType=powerInfo.querySuperRoleByOpId(op.getSuperiorId());
					if(roleType.equals(Role.SYSTEM.getCode())||
						roleType.equals(Role.O_MANAGER.getCode())){
						
					}else{
						addActionMessage("无权限访问");
						return ERROR;
					}
				}
				publicMethod(opMchtCd);
				dicMap=yyCardService.findDicnationary("1");
				contact=yyCardService.findScanCodeExist(opMchtCd);
				logger.info("页面初始化");
				if(contact==null){
					return SUCCESS;
				}
				if(!contact.getRemark3().equals("0")){
					Map<String,String> wxMap=yyCardService.getWx(merinfo);
					getRequest().setAttribute("wxNum",wxMap.get("WX"));
					getRequest().setAttribute("wxName",wxMap.get("WXN"));
				}
				return "again";
			}
			addActionMessage("无权限访问!");			
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return ERROR;
	}
	
	/**
	 * 查询是否已经入驻并绑卡
	 * @return
	 */
	@Action(value = "checkScanCodeStatus",results={@Result(type="json")})
	public String checkScanCodeStatus()
	{
		try {
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			contact=yyCardService.findScanCodeExist(opMchtCd);
			if(contact!=null){
				scanCodeFlag="1";//已绑卡
				logger.info("商户号【"+opMchtCd+"】已绑卡");
			}else{
				scanCodeFlag="0";//未绑卡
				logger.info("商户号【"+opMchtCd+"】未绑卡");
			}
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	/**
	 * 查询是否开通一一卡
	 * @return
	 */
	@Action(value = "checkYYCodeStatus",results={@Result(type="json")})
	public String checkYYCodeStatus()
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		NameValuePair[] nameValuePair=new NameValuePair[1];
		nameValuePair[0]=new NameValuePair("merchantNo",op.getAccountNo());
		JSONObject responsJson=HttpClientUtil.QRcode(nameValuePair,Utils.getConfigValue("url_QRcode"));
		if(responsJson!=null){
			String resultCode=responsJson.getJSONObject("result").get("resultCode").toString();
			if(resultCode.equals("0000")){
				//已开通
				flag="1";
				logger.info("商户号【"+op.getAccountNo()+"】已开通一一卡");
				return SUCCESS;
			}else{
				if(resultCode.equals("0008"))
				{
					flag="0";
					logger.info("商户号【"+op.getAccountNo()+"】未开通一一卡");
				}
				else{//除了0008
					flag="2";//传递参数异常
					logger.info("一一卡查询返回参数异常");
				}
			}
		}else{
			flag="3";//网络异常
			logger.info("一一卡查询网络异常");
		}
		return SUCCESS;
	}
	
	/**
	 * 商户类目
	 * @return
	 */
	@Action(value = "categoryType",results={@Result(type="json",params={"root","listMap"})})
	public String getCategory()
	{
		if(stairname!=null&&moversname==null)
		{
			listMap=yyCardService.categoryFirstType(stairname);
		}
		else if(stairname!=null&&moversname!=null){
			listMap=yyCardService.categoryFirstType(stairname, moversname);
		}
		return SUCCESS;
	}
	/**
	 * 调用远程接口开通一一卡
	 * @return
	 */
	@Action(value = "sendParams", results = { @Result(name = "success", location = "/pages/yycard/successQR.jsp"),
			@Result(name = "openCard", location = "/pages/yycard/openCard.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String openYYcard(){
		try{
			realCode=String.valueOf(getSession().getAttribute("yymsgCode"));
		if(realCode.equals("0")){
			addActionMessage("发送验证码失败");
			logger.info("验证码发送失败");
		}else if(!realCode.equals(scode)){
			addActionMessage("验证码不正确");
			logger.info("验证码不正确");
		}else{		
			Map<String,String> map=ConfigProperties.getSysDB1("UP_BC_CD",true);
			String bankCode=yycard.getBankBranchId().substring(0, 3);
			yycard.setBankId(bankCode);
			yycard.setBankName(map.get(bankCode));
			yycard.setPassword(MD5Utils.MD5Encode("123456"));
			yycard.setModifyFlag("1");//添加
			//请求远程接口
			JSONObject responsJson=HttpClientUtil.HttpRequstJSON(yycard,Utils.getConfigValue("url_register"));
			if(responsJson!=null)
			{
				String resultCode=responsJson.getJSONObject("result").get("resultCode").toString();
				if("0000".equals(resultCode))//成功
				{
					logger.info("开通成功!!!");
					return SUCCESS;
				}
				//{"result":{"message":"银行卡二要素验证失败","resultCode":"0005"}}
				else if(responsJson.getJSONObject("result").containsKey("message"))
				{
					String message=responsJson.getJSONObject("result").getString("message");
					msg=message;
					logger.info(message);
				}else{
					msg="开通失败!";
					logger.info("【"+yycard.getMerchantNo()+"】开通失败,请求返回参数异常!!!");
				}
			}else{			
				msg="请求超时,请重新尝试~";
				logger.info("开通失败,请求返回参数为空,请求超时~");
			}		
		}
		getRequest().setAttribute("msgFlag", "1");
		publicMethod(yycard.getMerchantNo());
		yycard.setCategoryId("0");
	}catch(Exception e)
		{
			logger.info("开通异常!!!");
			addActionError("开通异常!!!");
			e.getStackTrace();
			return ERROR;
		}
		return "openCard";
	}
	/**
	 * 查看一一卡二维码
	 * @return
	 */
	@Action(value = "cardQRcode", results = { @Result(name = "success", location = "/pages/yycard/QRcode.jsp")
			,@Result(name="error",location="/error.jsp")}
	)
	public String checkCardQRcode()
	{
		/**
		 * 调用http请求访问远程接口返回二维码图片信息
		 */
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(!logingMerchant.getRoleType().equals(Role.MERCHANT.getCode()))
		{
			addActionMessage("当前操作员非商户,不能操作");
			return ERROR;
		}
		//logingMerchant.setAccountNo("850110154110000");//测试数据850290007420056
		NameValuePair[] nameValuePair=new NameValuePair[1];
		nameValuePair[0]=new NameValuePair("merchantNo",logingMerchant.getAccountNo());
		JSONObject responsJson=HttpClientUtil.QRcode(nameValuePair,Utils.getConfigValue("url_QRcode"));	
		if(responsJson!=null)
		{
			String resultCode=responsJson.getJSONObject("result").get("resultCode").toString();
			if(resultCode.equals("0000"))
			{
				JSONObject beans=responsJson.getJSONObject("resultBean");
				qrUrl= beans.get("qrUrl").toString();
				yycard = new YYCardBean();
				yycard.setMobileNo(beans.getString("mobileNo"));
				yycard.setMerchantName(beans.getString("merchantName"));
				logger.info("查询二维码信息成功!");
				return SUCCESS;
			}
			else{
				if(resultCode.equals("0008"))
				{
					logger.info("一一卡未开通!");
					addActionError("请先开通一一卡!");
				}
				else{
					logger.info("查询商户号【"+logingMerchant.getAccountNo()+"】是否开通失败!!!");
					addActionMessage("查询是否开通失败");
					return ERROR;
				}
			}
		}
		else{
			logger.info("查询商户号【"+logingMerchant.getAccountNo()+"】是否开通失败!!!");
			addActionMessage("请求超时,请重新尝试~");
			return ERROR;
		}
		return ERROR;
	}
	
	/***
	 * 发送报文入驻并绑卡
	 * @return
	 */
	@Action(value = "sendScanCode", results = { @Result(name = "success", location = "/pages/yycard/successQR.jsp")
		,@Result(name = "message", location = "/pages/yycard/openCard.jsp")
		,@Result(name="error",location="/error.jsp")})
	public String registerScanCode(){
		try {
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.SYSTEM.getCode())||
					op.getRoleType().equals(Role.O_MANAGER.getCode())||
					op.getRoleType().equals(Role.AGENT.getCode())||
					op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
					
				if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){//运营先行判断
					String roleType=powerInfo.querySuperRoleByOpId(op.getSuperiorId());
					if(roleType.equals(Role.SYSTEM.getCode())||
						roleType.equals(Role.O_MANAGER.getCode())){
						
					}else{
						addActionMessage("无权限访问");
						return ERROR;
					}
				}
					publicMethod(opMchtCd);
					merinfo.setPictrueList(pictrueList);
					merinfo.setProvCd(dic.getProvice());
					merinfo.setCityCd(dic.getCity());
					merinfo.setAreaCd(dic.getArea());
					Map<String, Object> result=yyCardService.sendScanCodeMessage(merinfo,yycard,op);
					dicMap=yyCardService.findDicnationary("1");
					msg=String.valueOf(result.get("message"));
					addActionMessage(msg);
					if("".equals(result.get("status"))){					
						return "message";
						}
					return SUCCESS;
			}
			addActionMessage("无权限访问");			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
		return ERROR;
	}
	
	/**
	 * 重新入驻
	 * @return
	 */
	@Action(value = "sendScanCodeAgain", results = { @Result(name = "success", location = "/pages/yycard/successQR.jsp")
	,@Result(name = "message", location = "/pages/yycard/againCard.jsp")
	,@Result(name="error",location="/error.jsp")})
	public String registerScanCodeAgain(){
		try {
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.SYSTEM.getCode())||
					op.getRoleType().equals(Role.O_MANAGER.getCode())||
					op.getRoleType().equals(Role.AGENT.getCode())||
					op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
					
				if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){//运营先行判断
					String roleType=powerInfo.querySuperRoleByOpId(op.getSuperiorId());
					if(roleType.equals(Role.SYSTEM.getCode())||
						roleType.equals(Role.O_MANAGER.getCode())){
						
					}else{
						addActionMessage("无权限访问");
						return ERROR;
					}
				}
					publicMethod(contact.getMchtCd());
					if(yycard==null){
						yycard=new YYCardBean();
					}
					Map<String, Object> result=yyCardService.openCardAgain(merinfo, yycard, op, openType);
					msg=String.valueOf(result.get("msg"));
					addActionMessage(msg);
					if("".equals(result.get("status"))){
						contact=yyCardService.findScanCodeExist(contact.getMchtCd());
						/*Map<String,String> wxMap=yyCardService.getWx(merinfo);
						getRequest().setAttribute("wxNum",wxMap.get("WX"));
						getRequest().setAttribute("wxName",wxMap.get("WXN"));*/
						return "message";
						}
					return SUCCESS;
			}
			addActionMessage("无权限访问");			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
		return ERROR;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return null;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return null;
	}

	@Override
	protected String getInitPageSize() {
		return null;
	}

	public TblMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblMchtInf merinfo) {
		this.merinfo = merinfo;
	}
	public YYCardBean getYycard() {
		return yycard;
	}
	public void setYycard(YYCardBean yycard) {
		this.yycard = yycard;
	}
	public String getStairname() {
		return stairname;
	}
	public void setStairname(String stairname) {
		this.stairname = stairname;
	}
	public String getMoversname() {
		return moversname;
	}
	public void setMoversname(String moversname) {
		this.moversname = moversname;
	}
	public List<Map<String, Object>> getListMap() {
		return listMap;
	}
	public void setListMap(List<Map<String, Object>> listMap) {
		this.listMap = listMap;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public String getFlag() {
		return flag;
	}
	public void setFlag(String flag) {
		this.flag = flag;
	}
	
	public String getScode() {
		return scode;
	}
	public void setScode(String scode) {
		this.scode = scode;
	}
	public String getQrUrl() {
		return qrUrl;
	}
	public void setQrUrl(String qrUrl) {
		this.qrUrl = qrUrl;
	}
	
	public String getScanCodeFlag() {
		return scanCodeFlag;
	}

	public void setScanCodeFlag(String scanCodeFlag) {
		this.scanCodeFlag = scanCodeFlag;
	}
	
	public List<TblMchtPicture> getPictrueList() {
		return pictrueList;
	}

	public void setPictrueList(List<TblMchtPicture> pictrueList) {
		this.pictrueList = pictrueList;
	}

	public List<ScanCodeDictionary> getDicMap() {
		return dicMap;
	}

	public void setDicMap(List<ScanCodeDictionary> dicMap) {
		this.dicMap = dicMap;
	}

	public TblMchtContact getContact() {
		return contact;
	}

	public void setContact(TblMchtContact contact) {
		this.contact = contact;
	}
	
	public String getOpenType() {
		return openType;
	}

	public void setOpenType(String openType) {
		this.openType = openType;
	}

	public String getRealCode() {
		return realCode;
	}
	public void setRealCode(String realCode) {
		this.realCode = realCode;
	}		

	public ScanCodeDictionary getDic() {
		return dic;
	}

	public void setDic(ScanCodeDictionary dic) {
		this.dic = dic;
	}

	//公共方法
	protected void publicMethod(String merchantNo)
	{
		try {
			merinfo=yyCardService.queryMerinfoInfoById(merchantNo);
			List<Map<String, Object>> listMap=yyCardService.categoryFirstType();
			getRequest().setAttribute("stairname", listMap);
		} catch (ServiceException e) {
			logger.info("查询商户【"+merchantNo+"】信息失败");
			e.printStackTrace();
		}
	}
	/**
	 * 发短信验证手机号
	 * @return
	 */
	@Action(value = "sendMessage",results={@Result(type="json")})
	public String sendMessage()
	{	
		try {
			if(yycard!=null){
			 realCode=Constance.randomNums(6);//生成验证码
			 boolean result = yyCardService.sendMsg(yycard.getMobileNo(),realCode);			
			 if(!result){
				 realCode="0";
			 }
			 getSession().setAttribute("yymsgCode", realCode);//向session存入短信验证码
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 * 加载省市县
	 * @return
	 */
	@Action(value = "loadPCA",results={@Result(type="json",params={"root","dicMap"})})
	public String loadCode(){
		
		try {
			dicMap=yyCardService.findDicnationary(dic.getPcode());
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}

	public String getOpMchtCd() {
		return opMchtCd;
	}

	public void setOpMchtCd(String opMchtCd) {
		this.opMchtCd = opMchtCd;
	}
		
}
